package org.client.iot.ui.project.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.view.View;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.textfield.TextInputEditText;
import com.lucky.base.network.NetworkApi;
import com.lucky.base.network.observer.BaseObserver;
import com.lucky.utils.FastjsonUtils;
import com.lucky.utils.log.LogUtils;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import org.client.iot.R;
import org.client.iot.databinding.FragmentProjectHomeBinding;
import org.client.iot.domain.ProjectDto;
import org.client.iot.http.ApiService;
import org.client.iot.http.BaseRes;
import org.client.iot.http.UpdateReqDto;
import org.client.iot.ui.project.ProjectManagerActivity;
import org.client.iot.ui.project.adapter.ProjectListAdapter;
import org.client.iot.util.MMKVUtils;
import org.client.iot.util.PermissionManager;
import org.tzw.template.base.BaseFragment;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import cn.hutool.core.collection.CollUtil;
import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.RequestBody;


public class ProjectHomeFragment extends BaseFragment<FragmentProjectHomeBinding> {
    private ProjectListAdapter projectListAdapter;
    private LocationManager locationManager;
    private final int pageSize = 10; // 数据量
    private int pageNum = 1; // 页码
    private int total;

    @Override
    protected void initData(View view) {
        projectListAdapter = new ProjectListAdapter(requireActivity(), new ArrayList<>());
        locationManager = (LocationManager) requireActivity().getSystemService(Context.LOCATION_SERVICE);

    }

    @Override
    protected void initView(View view) {
        LinearLayoutManager manager = new LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false);
        mRoot.recProjectList.setLayoutManager(manager);
        mRoot.recProjectList.setAdapter(projectListAdapter);
        mRoot.recProjectList.addItemDecoration(new DividerItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL));
        projectListAdapter.setEmptyView(R.layout.activity_empty);
        getProjectList(pageNum, pageSize);

    }

    // 检查权限后获取位置
    @SuppressLint("MissingPermission")
    private String getLocation() {
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location == null) {
            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        if (location != null) {
            String latitude = String.valueOf(location.getLatitude());
            String longitude = String.valueOf(location.getLongitude());
            // 使用获取到的经纬度
            return latitude + "=" + longitude;
        }
        return "";
    }

    @Override
    protected void initListener() {
        //上拉加载更多
        projectListAdapter.getLoadMoreModule().setPreLoadNumber(1);
        projectListAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
        projectListAdapter.getLoadMoreModule().setOnLoadMoreListener(() -> {
            if (total <= pageNum * pageSize) {
                projectListAdapter.getLoadMoreModule().loadMoreEnd();
                return;
            }
            getProjectList(pageNum + 1, pageSize);
        });
        projectListAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(requireActivity(), ProjectManagerActivity.class);
            intent.putExtra("projectName", projectListAdapter.getData().get(position).getName());
            intent.putExtra("projectId", projectListAdapter.getData().get(position).getId());
            startActivity(intent);
        });
        getBinding().imgAddProject.setOnClickListener(v -> {
            PermissionManager.checkPermission(getActivity(), new PermissionManager.AcceptPermissionListener() {
                @Override
                public void onSuccess() {
                    MaterialDialog materialDialog = new MaterialDialog.Builder(requireActivity()).title("新建项目").customView(R.layout.dialog_project_home_add_item, true).positiveText("确定").callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog dialog) {
                            TextInputEditText projectNameEdit = dialog.findViewById(R.id.textInput_project_name);
                            TextInputEditText projectAddressEdit = dialog.findViewById(R.id.textInput_project_address);

                            String project_name = Objects.requireNonNull(projectNameEdit.getText()).toString();
                            String project_address = Objects.requireNonNull(projectAddressEdit.getText()).toString();

                            String data = getLocation();
                            String latitude = "";
                            String longitude = "";
                            if (project_name.isEmpty() || project_address.isEmpty()) {
                                showToastShort("请填写完整信息");
                                return;
                            }
                            if (!data.isEmpty()) {
                                latitude = data.split("=")[0];
                                longitude = data.split("=")[1];
                                addProject(project_name, project_address, latitude, longitude, "");
                            }

                            LogUtils.d(TAG, "项目名称：" + project_name + "=项目地址：" + project_address + "=经度:" + latitude + "==纬度:" + longitude);
                        }
                    }).show();
                }

                @Override
                public void onFail() {
                    showToastShort("获取位置权限不完整，请先获取对应权限");
                }

                @Override
                public void onError(Throwable e) {

                }
            }, PermissionManager.getLOCATIONPermission());


        });
    }

    // 获取项目列表
    private void getProjectList(int page, int pageSize) {
        String token = "Bearer " + MMKVUtils.getInstance().get("token", "");
        Observable<BaseRes<ProjectDto>> compose = NetworkApi.createService(ApiService.class, "")
                .getProjectList(token, page, pageSize).compose(NetworkApi.applySchedulers(new BaseObserver<BaseRes<ProjectDto>>() {
                    @SuppressLint({"CheckResult", "NotifyDataSetChanged"})
                    @Override
                    public void onSuccess(BaseRes<ProjectDto> req) {
                        if (req == null) {
                            return;
                        }
                        requireActivity().runOnUiThread(() -> {
                            LogUtils.i("获取项目列表req==", FastjsonUtils.toJsonString(req));
                            total = req.getTotal();
                            List<ProjectDto> reqRows = req.getRows();
                            if(CollUtil.isEmpty(reqRows)){
                                return;
                            }
                            projectListAdapter.addData(req.getRows());
                            pageNum = page;
                            if (total <= pageNum * pageSize) {
                                projectListAdapter.getLoadMoreModule().loadMoreEnd();
                            }else {
                                projectListAdapter.getLoadMoreModule().loadMoreComplete();
                            }


                            if (req.getCode() == 401) {
                                showToastLong("登录已过期，请重新登录");
                                MMKVUtils.getInstance().put("token", "");
                                requireActivity().finish();
                            }
                        });
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onFailure(Throwable e) {
                        requireActivity().runOnUiThread(() -> {
                            showToastLong(e.getMessage());
                            if (page > 1) {
                                pageNum--;
                            }
                        });
                    }

                }));
    }

    /**
     * 添加项目
     *
     * @param name              项目名称
     * @param address           项目地址
     * @param locationLongitude 位置经度
     * @param locationLatitude  位置纬度
     * @param remark            项目描述
     */
    private void addProject(String name, String address, String locationLongitude, String locationLatitude, String remark) {
        String token = "Bearer " + MMKVUtils.getInstance().get("token", "");
        String params = FastjsonUtils.toJsonString(addProParams(name, address, locationLongitude, locationLatitude, remark));
        Observable<UpdateReqDto> compose = NetworkApi.createService(ApiService.class, "").addProject(token, RequestBody.create(MediaType.parse("application/json"), params)).compose(NetworkApi.applySchedulers(new BaseObserver<UpdateReqDto>() {
            @SuppressLint("CheckResult")
            @Override
            public void onSuccess(UpdateReqDto req) {
                if (req == null) {
                    return;
                }
                requireActivity().runOnUiThread(() -> {
                    LogUtils.i("添加项目req==", req.toString());
                    showToastShort(req.getMsg());
//                    pageNum = 1;
//                    total = 0;
//                    projectListAdapter.setList(new ArrayList<>());
                    getProjectList(pageNum, pageSize);
                });

            }

            @SuppressLint("CheckResult")
            @Override
            public void onFailure(Throwable e) {
                requireActivity().runOnUiThread(() -> showToastLong(e.getMessage()));
            }
        }));
    }

    private Map<String, Object> addProParams(String name, String address, String locationLongitude, String locationLatitude, String remark) {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("name", name);
        params.put("address", address);
        params.put("locationLongitude", locationLongitude);
        params.put("locationLatitude", locationLatitude);
        params.put("remark", remark);
        return params;
    }
}